﻿jQuery.stockselector = function(input, value, callback1, callback2)
{
    var $input = $(input);

    $input.autocomplete(      
    "/securities/ajax_autocomplete",      
    {  			
        delay:10,			
        minChars:1,			
        matchSubset:1,		
        matchContains:false,
        cacheLength:10,
        lineSeparator:"\n",
        selectFirst:true,
        onItemSelect:selectitem,
        onFindValue:findvalue,
        formatItem:formatitem,
        autoFill:false,
        cellSeparator:"|"
    });
    
    if (value != "")
    {
      $.post("/securities/ajax_autocomplete",{q:value,t:Math.random()},function(data){
        if (data != "false")
        {
          var dataarray = data.split("|");
          $input.val(value);
          if (callback1) setTimeout(function() { callback1(dataarray[1], dataarray[2], value) }, 1);
        }      
      },"TEXT");
    }
    
    function findvalue(li)
    {
      if(li == null) return alert("数据错误"); 
      if(!!li.extra)
      {
 	     if (callback1) setTimeout(function() { callback1(li.extra[0], li.extra[1], $input.val()); }, 1);
      }
      else
      {
        $input.val("");
        if (callback2) setTimeout(function() { callback2(); }, 1);
      }    
    }

    function selectitem(li) 
    {
      findvalue(li);
    }

    function formatitem(row) 
    {
      if(row[0] == "false") return "没有找到对应的证券";
      else return "<div>"+row[0]+" "+row[1]+"</div>";
    } 
}

jQuery.fn.stockselector = function(value, callback1, callback2) {
    this.each(function() {
		var input = this;
		new jQuery.stockselector(input, value, callback1, callback2);
	});
}
